#!/bin/sh
#
# Linux RealPort Post Install script.
# Should be run after make install.
#
# 1) Will be called automagically by rpm -i.
# 2) Needs to be called manually for the tar.gz install
#    by doing a "make postinstall"

# Let the system know about our scripts in /etc/rc.d/init.d/
# NB:  RHEL has some hokey chkconfig backward compat stuff even with
# the systemctl stuff.  If systemd/systemctl is available, prefer that.

if systemctl --version >/dev/null  ; then
# compat layer to pick up sysV init.s/ scripts
	/lib/systemd/system-generators/systemd-sysv-generator
# kick systemd to see the new service files, and enable.
	systemctl daemon-reload
	systemctl enable dgrp_daemon
	systemctl enable dgrp_ditty
	echo "Added RealPort (dgrp) scripts to systemd startup"
elif [ -x /sbin/chkconfig ]; then
	/sbin/chkconfig --add dgrp_daemon
	/sbin/chkconfig --add dgrp_ditty
	echo "Added RealPort (dgrp) scripts to SysV system startup"
else
	echo "RealPort (dgrp) startup scripts must be manually installed -- see release notes"
fi


# Convert old style config to new style config if needed...
if [ -f /etc/dgrp.backing.store ]
then
	echo "Converting config file..."
	#rm -f /tmp/dgrp.backing.store.new
	rm -f /tmp/dgrp/dgrp.backing.store.new
	mkdir -p /tmp/dgrp

	while read id ip pcnt speed ipport mode owner grp encrypt encrypt_ipport rest
	do
		firstchar=`expr "${id}#" : '\(.\).*'`
		case $firstchar in
		'#')
			printf "$id $ip $pcnt $speed $ipport $mode $owner $grp $encrypt $encrypt_ipport $rest\n" >> /tmp/dgrp/dgrp.backing.store.new
			continue;
		esac

		if [ -z "$encrypt" ]
		then
			encrypt="never"
		fi

		if [ -z "$encrypt_ipport" ]
		then
			encrypt_ipport="default"
		fi

		#Separate format string to disable shell expansions (such as %e) in the variables
		printf "%s %s %s %s %s %s %s %s %s %s %s\n" $id $ip $pcnt $speed $ipport $mode $owner $grp $encrypt $encrypt_ipport $rest >> /tmp/dgrp/dgrp.backing.store.new

	done < /etc/dgrp.backing.store

	mv /etc/dgrp.backing.store /etc/dgrp.backing.store.old
	#mv /tmp/dgrp.backing.store.new /etc/dgrp.backing.store
	mv /tmp/dgrp/dgrp.backing.store.new /etc/dgrp.backing.store
fi

# Create any symlinks we want
if [ ! -e /usr/bin/dgrp_cfg_node ]
then
	ln -s /usr/bin/dgrp/config/dgrp_cfg_node /usr/bin/dgrp_cfg_node
fi

if [ ! -e /usr/bin/dgrp_gui ]
then
	ln -s /usr/bin/dgrp/config/dgrp_gui /usr/bin/dgrp_gui
fi

if [ ! -e /usr/bin/ditty ]
then
	ln -s /usr/bin/ditty-rp /usr/bin/ditty
fi

if [ ! -e /usr/bin/dinc ]
then
	ln -s /usr/bin/dinc.dgrp /usr/bin/dinc
fi         


# Finally, force dependency checks
if [ -e /sbin/depmod ]
then
	/sbin/depmod -a
fi
